const db = wx.cloud.database()
const _ = db.command
const collectionName = 'point'
export default {
  get: async function ({
    openid
  }) {
    let res = await db.collection(collectionName).where({
      openid
    }).get()
    return res.data[0]
  },
  add: async function (data) {
    data.createDate = new Date()
    return await db.collection(collectionName).add({
      data: data
    })
  },

  update: async function (data) {
    var id = data.id
    delete data.id

    var res = await db.collection(collectionName).doc(id).update({
      data: data
    })
    return res
  },

  delete: async function (id) {
    var res = await db.collection(collectionName).doc(id).remove()
    return res
  },

  async addNum({
    openid,
    num
  }) {
    let res = await this.get({
      openid
    })
    if (!res) {
      await this.add({
        openid,
        count: 0
      })
    }
    await db.collection(collectionName).where({
      openid
    }).update({
      data: {
        count: _.inc(num)
      }
    })
  },

  async exchange({
    openid,
    goodsId,
    orderItem,
    address,
    content
  }) {
    return await wx.cloud.callFunction({
      name: 'cloud',
      data: {
        url: '/point/exchange',
        openid,
        goodsId,
        orderItem,
        address,
        content
      }
    })

  }
}